import React, { useEffect, useState } from 'react';
import router from 'umi/router';
import {
  Table, Modal, Form, Input, Col, message, Select, DatePicker, Button, Row, InputNumber, Icon, Upload,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  getStoreInfoList, getStoreInfo, deleteStoreInfo, saveStoreInfo,
} from '@/services/rentCenter/inverstment';
import {
  getBusinessById,
} from '@/services/rentCenter/basicSet';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';
import button from '@/pages/setting/auth/button';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const { Search } = Input
const { RangePicker } = DatePicker

const addMyContract = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [stores, setstores] = useState([]);
  const [contractType, setcontractType] = useState('1');
  const [moneyTypes, setmoneyTypes] = useState([
    { id: '1', fundName: '定金' },
    { id: '2', fundName: '税' },
    { id: '3', fundName: '保证金' },
  ]);
  const [contractDate, setcontractDate] = useState([]);
  const [contractDate2, setcontractDate2] = useState([]);
  const [columnsdata1, setcolumnsdata1] = useState([]);
  const [columnsdata2, setcolumnsdata2] = useState([{
    fundTypeId: '',
    startTime: '',
    endTime: '',
    money: 0,
    collectMoney: 0,
    collectDate: '',
    timeDisabled: false,
    fundMoneyName: '',
    index: 0,
  }]);
  const [columnsdata3, setcolumnsdata3] = useState([]);
  const [shoppers, setshoppers] = useState([]);
  const [firstId, setfirstId] = useState(undefined);
  const [shops, setshops] = useState([]);
  const [shopCondition, setshopCondition] = useState('');
  const [shopData, setshopData] = useState([]);
  const [fileList, setfileList] = useState([]);
  const [checkedData, setcheckedData] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({
    type: '0',
  });
  const [showtype2, setshowtype2] = useState(false);
  const [showFiles, setshowFiles] = useState(false);
  const [types, settypes] = useState([]);
  const [supplierTypes, setsupplierTypes] = useState([
    {
      label: '连锁经营',
      value: '1',
    },
    {
      label: '个人经营',
      value: '0',
    },
  ]);
  const [types2, settype2s] = useState([]);
  const [brands, setbrands] = useState([]);
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  const [previewVisible, setpreviewVisible] = useState(false);
  const [previewImage, setpreviewImage] = useState('');
  const [chooseShop, setchooseShop] = useState(false);
  const delete1 = v => {
    console.log(v)
  }
  const delete2 = v => {
    columnsdata2.splice(v, 1)
    let arr = []
    for (let i = 0; i < columnsdata2.length; i++) {
      arr.push({ ...columnsdata2[i], index: i })
    }
    setcolumnsdata2(arr)
  }
  const delete3 = v => {
    console.log(v)
  }
  const chooseShops = [
    {
      title: '序号',
      type: 'index',
      align: 'center',
      width: 70,
    },
    {
      title: '商铺号',
      align: 'center',
      key: 'shopNumber',
    },
    {
      title: '楼栋',
      align: 'center',
      key: 'building',
    },
    {
      title: '楼层',
      align: 'center',
      key: 'floor',
    },
    {
      title: '计租面积（㎡）',
      align: 'center',
      key: 'rentingArea',
    },
  ];
  const columns1 = [
    {
      title: '序号',
      type: 'index',
      align: 'center',
      width: 70,
    },
    {
      title: '商铺号',
      align: 'center',
      key: 'shopNumber',
    },
    {
      title: '楼栋',
      align: 'center',
      key: 'building',
    },
    {
      title: '楼层',
      align: 'center',
      key: 'floor',
    },
    {
      title: '计租面积（㎡）',
      align: 'center',
      key: 'rentingArea',
    },
    {
      title: '操作',
      align: 'center',
      key: 'handle',
      render: (p, r, i) => (
        <Button type="danger" onClick={delete1(i)}>删除</Button>
      ),
    },
  ];
  const columns2 = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      key: 'index',
    },
    {
      title: '款项类型',
      key: 'moneyTypes',
      align: 'center',
      render: (p, r, i) => (
        <Select style={{ width: '100%' }} onChange={v => {
          columnsdata2[i].moneyTypes = v
          moneyTypes.forEach(vl => {
            if (vl.id === v) {
              if (vl.fundName === '保证金') {
                columnsdata2[i].timeDisabled = true
              } else {
                columnsdata2[i].timeDisabled = false
              }
            }
          })
          setcolumnsdata2([...columnsdata2])
        }}>{ moneyTypes.map(mo => (<Option key={mo.id}>{mo.fundName}</Option>)) }</Select>
      ),
    },
    {
      title: '款项时间',
      key: 'startTime',
      align: 'center',
      render: (p, r, i) => (<RangePicker placeholder={['开始时间', '结束时间']} disabled={r.timeDisabled} onChange={(v, t) => {
          columnsdata2[i].startTime = t[0]
          columnsdata2[i].endTime = t[1]
          setcolumnsdata2([...columnsdata2])
        }} />),
    },
    {
      title: '金额（元）',
      key: 'money',
      align: 'center',
      render: (p, r, i) => (
        <InputNumber min={0} onChange={v => {
          columnsdata2[i].money = v
          setcolumnsdata2([...columnsdata2])
        }} />
      ),
    },
    {
      title: '应收金额（元）',
      key: 'collectMoney',
      align: 'center',
      render: (p, r, i) => (
        <InputNumber min={0} onChange={v => {
          columnsdata2[i].collectMoney = v
          setcolumnsdata2([...columnsdata2])
        }} />
      ),
    },
    {
      title: '计划收款日期',
      key: 'collectDate',
      align: 'center',
      render: (p, r, i) => (
        <DatePicker onChange={(v, t) => {
          columnsdata2[i].collectDate = t
          setcolumnsdata2([...columnsdata2])
        }} />
      ),
    },
    {
      title: '操作',
      key: 'handle',
      align: 'center',
      render: (p, r, i) => (
        <Button type="danger" onClick={delete2.bind(this, i)}>删除</Button>
      ),
    },
  ];
  const columns3 = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      key: 'index',
    },
    {
      title: '门店名称',
      key: 'name',
      align: 'center',
    },
    {
      title: '门店编号',
      key: 'storeNumber',
      align: 'center',
    },
    {
      title: '所属商户',
      key: 'merchantsName',
      align: 'center',
    },
    {
      title: '签约状态',
      key: 'signStatus',
      render: params => (
        <span>{params.signStatus === 1 ? '已签约' : '未签约'}</span>
      ),
    },
  ];
  // 列表
  const getList = async params => {
    const r = await getStoreInfoList(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
    if (r.data && r.data.length) {
      settypes(r.data)
    }
  };
  useEffect(() => {
    getList(listQuery);
    console.log(props.location)
    if (props.location.query.i) {
      setcontractType(props.location.query.i)
    }
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  // const removeRole = async record => {
  //   deleteShopCat({
  //     id: record.id,
  //   }).then(res => {
  //     if (res.data.code === '0') {
  //       const index = data.findIndex(e => e.id === record.id);
  //       setColData(() => {
  //         data.splice(index, 1);
  //         return [...data];
  //       });
  //     }
  //   })
  // };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  const getType2 = () => {
    getBusinessById({ id: listQuery.businessId }).then(r => {
      if (r.data && r.data.code === '0') {
        settype2s(r.data.data)
      }
    })
  }
  const storechange = v => {
    console.log(v)
  }
  const typeChange = v => {
    setfirstId(v)
    if (v) {
      if (!types2) {
        setshowtype2(true)
      }
      getType2()
    } else {
      settype2s([])
      setshowtype2(false)
    }
  }
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="模糊条件">
          <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} value={listQuery.condition} placeholder="门店名称，编号，联系人，联系电话，关联商户，招商员" />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="品牌">
          <Select onChange={v => { setListQuery({ ...listQuery, brandId: v }) }} placeholder="请选择品牌" value={listQuery.brandId}>
            { brands.map(v => (<Option key={v.id}>{v.name}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="签约状态">
          <Select onChange={v => { setListQuery({ ...listQuery, signStatus: v }) }} placeholder="请选择签约状态" value={listQuery.signStatus}>
            <Option key={0} value={0}>未签约</Option>
            <Option key={1} value={1}>已签约</Option>
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="一级业态">
          <Select onChange={typeChange} placeholder="请选择一级业态" value={firstId}>
            { types.map(v => (<Option key={v.id}>{v.name}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="二级业态">
          <Select onChange={v => { setListQuery({ ...listQuery, businessId: v }) }} placeholder="请选择二级业态" value={listQuery.businessId}>
            { types2.map(v => (<Option key={v.id}>{v.name}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = values
        params.status ? params.status = '1' : params.status = '0'
        console.log('Received values of form: ', values);
        saveStoreInfo({ storeBusiness: params }).then(() => {
          getList(listQuery)
          setState(!isShow);
        })
      }
    });
  };
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  const handleChange = v => {
    setfileList(v.fileList)
  }
  const handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setpreviewImage(file.url || file.preview)
    setpreviewVisible(true)
  }
  // 清空查询条件
  const handleReset = () => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
    })
    setfirstId(undefined)
    setshowtype2(false)
    getList({
      pageNo: 1,
      pageSize: 10,
    })
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      default:
        return ''
    }
  };
  const catchange = v => {
    console.log(v)
  }
  const rowSelection = {
    type: 'checkbox',
    onChange: (selectedRowKeys, selectedRows) => {
      checkedData(selectedRows)
    },
  };
  const time1 = (v, t) => {
    console.log(t)
    setListQuery({ ...listQuery, hireStart: t[0], hireEnd: t[1] })
    setcontractDate(v)
  }
  const time2 = (v, t) => {
    console.log(t)
    setListQuery({ ...listQuery, rentStart: t[0], rentEnd: t[1] })
    setcontractDate2(v)
  }
  const addKuan = () => {
    let arr = []
    for (let i = 0; i <= columnsdata2.length; i++) {
      if (i < columnsdata2.length) {
        arr.push({ ...columnsdata2[i], index: i })
      } else {
        arr.push({
          fundTypeId: '',
          startTime: '',
          endTime: '',
          money: 0,
          collectMoney: 0,
          collectDate: '',
          timeDisabled: false,
          fundMoneyName: '',
          index: i,
        })
      }
    }
    setcolumnsdata2(arr)
  }
  const saveDraft = () => {
    console.log('保存草稿')
  }
  const submitInfo = () => {
    console.log('````提交审核``````')
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    })
  }
  const uploadButton = (
    <div>
      <Icon type="plus" />
      <div className="ant-upload-text">上传凭证</div>
    </div>
  )
  return (
    <PageHeaderWrapper title="添加合同">
      <div className="abox">
        <p className="ctitle">基本信息</p>
        <Form {...formItemLayout}>
          <Row>
            <Col span={8}>
              <Form.Item label="合同编号">
                {getFieldDecorator('contractNumber', {
                  initialValue: info.contractNumber,
                  rules: [
                    {
                      required: true,
                      message: '请输入合同编号',
                    },
                  ],
                })(<Input placeholder="请输入合同编号" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="合同版本号">
                {getFieldDecorator('versionNumber', {
                  initialValue: info.versionNumber,
                })(<Input placeholder="请输入合同版本号" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="合同主题">
                {getFieldDecorator('contractTitle', {
                  initialValue: info.contractTitle,
                  rules: [
                    {
                      required: true,
                      message: '请输入合同主题',
                    },
                  ],
                })(<Input placeholder="请输入合同主题" />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="商户类型">
                {getFieldDecorator('type', {
                  initialValue: info.type,
                  rules: [
                    {
                      required: true,
                      message: '请选择商户类型',
                    },
                  ],
                })(<Select placeholder="请选择商户类型" onChange={v => { setInfo({ ...info, type: v }) }}>{ supplierTypes.map(v => (<Option key={v.value}>{v.label}</Option>)) }</Select>)}
              </Form.Item>
            </Col>
            { info.type === '1' ? (
              <>
                <Col span={8}>
                  <Form.Item label="商户名称">
                    {getFieldDecorator('merchantsName', {
                      initialValue: info.merchantsName,
                      rules: [
                        {
                          required: true,
                          message: '请输入商户名称',
                        },
                      ],
                    })(<Input placeholder="请输入商户名称" />)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="商户编号">
                    {getFieldDecorator('merchantsNumber', {
                      initialValue: info.merchantsNumber,
                    })(<Input disabled />)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="选择门店">
                    {getFieldDecorator('storeId', {
                      initialValue: info.storeId,
                    })(<Select placeholder="请选择门店" onChange={storechange}>{stores.map(v => (<Option key={v.id}>{v.businessName}</Option>))}</Select>)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="门店编号">
                    {getFieldDecorator('storeNumber', {
                      initialValue: info.storeNumber,
                    })(<Input disabled />)}
                  </Form.Item>
                </Col>
              </>
            ) : (
              <>
                <Col span={8}>
                  <Form.Item label="门店名称">
                    {getFieldDecorator('storeName', {
                      initialValue: info.storeName,
                      rules: [
                        {
                          required: true,
                          message: '请输入门店名称',
                        },
                      ],
                    })(<Input placeholder="请输入门店名称" />)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="门店编号">
                    {getFieldDecorator('storeNumber', {
                      initialValue: info.storeNumber,
                    })(<Input disabled />)}
                  </Form.Item>
                </Col>
              </>
            ) }
            <Col span={8}>
              <Form.Item label="合同租赁期">
                <RangePicker style={{ width: '100%' }} value={contractDate} onChange={time1} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="合同计租期">
                <RangePicker style={{ width: '100%' }} value={contractDate2} onChange={time2} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="合同租期（月）">
                {getFieldDecorator('hireTime', {
                  initialValue: info.hireTime,
                })(<Input placeholder="通过租赁期自动算出" disabled />)}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="合同签订日期">
                <DatePicker style={{ width: '100%' }} onChange={(v, t) => { setInfo({ ...info, signTime: t }) }} placeholder="请选择签订日期"/>
              </Form.Item>
            </Col>
            { contractType === '1' ? (
              <Col span={8}>
                <Form.Item label="租金总金额（元）">
                  {getFieldDecorator('rentSumMoney', {
                    initialValue: info.rentSumMoney,
                  })(<Input placeholder="关联商铺后自动计算得出" disabled />)}
                </Form.Item>
              </Col>
            ) : (
              <Col span={8}>
                <Form.Item label="物业费总金额（元）">
                  {getFieldDecorator('propertySumMoney', {
                    initialValue: info.propertySumMoney,
                  })(<Input placeholder="关联收款后自动计算得出" disabled />)}
                </Form.Item>
              </Col>
            ) }
            <Col span={8}>
              <Form.Item label="签订人">
                {getFieldDecorator('signName', {
                  initialValue: info.signName,
                })(<Input placeholder="请输入签订人" disabled />)}
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
      <div className="abox">
        <p className="ctitle">关联商铺</p>
        <div className="marginB20">
          <Button type="primary" onClick={() => { setchooseShop(true) }}>添加商铺</Button>
        </div>
        <Table columns={columns1} rowKey="index" />
      </div>
      <div className="abox">
        <p className="ctitle">关联款项</p>
        <div className="marginB20"><Button type="primary" onClick={addKuan}>添加款项</Button></div>
        <Table columns={columns2} dataSource={columnsdata2} rowKey="index" />
      </div>
      <div className="abox">
        <p className="ctitle">关联附件</p>
        <Upload
          action="/Amaidan-Goods-Web/common/uploadImage"
          accept="image/*"
          listType="picture-card"
          fileList={fileList}
          onPreview={handlePreview}
          onChange={handleChange}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
      </div>
      <div className="bottomFooter" style={{ marginTop: '1rem' }}>
        <Button type="primary" ghost onClick={saveDraft.bind(this)}>保存草稿</Button>
        <Button style={{ margin: '0 15px' }} type="primary" onClick={submitInfo.bind(this)}>提交审核</Button>
        <Button type="info" onClick={() => { router.goBack() }}>返回</Button>
      </div>
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
      </Modal>
      <Modal visible={previewVisible} footer={null} onCancel={() => { setpreviewVisible(false) }}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
      <Modal
        title="添加附件"
        visible={showFiles}
        onOk={handleSubmit.bind(this)}
        onCancel={() => setshowFiles(false)}
        destroyOnClose
      >
      </Modal>
      <Modal
        title="选择商铺"
        visible={chooseShop}
        width="80%"
        onOk={handleSubmit.bind(this)}
        onCancel={() => { setchooseShop(false) }}
        destroyOnClose
      >
        <div className="myflex marginB20">
          <div className="alable">模糊条件:</div>
          <Search
            style={{ width: 300 }}
            placeholder="楼栋，楼层，商铺号"
            enterButton="查找"
            onSearch={value => console.log(value)}
          />
        </div>
        <Table columns={chooseShops} dataSource={shopData} rowSelection={rowSelection} rowKey="index"></Table>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(addMyContract));
